/**
 * 
 */
package org.jinion.result.table;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jinion.exception.JinionException;

/**
 * This is the wrapper of ResultSet
 * @author zhlmmc
 *
 */
public abstract class AbstractTable {
	protected List<TableColumn> columns;
	protected List<TableRow> rows;
	protected ResultSet resultSet;
	
	public AbstractTable(ResultSet resultSet) throws JinionException{
		this.resultSet = resultSet;
		columns = new ArrayList<TableColumn>();
		rows = new ArrayList<TableRow>();
		buildTable();
	}
	/**
	 * Traversal the ResultSet to fill the table.
	 * This method will be called in the constructor of AbstractTable.
	 * @throws JinionException
	 */
	protected abstract void buildTable() throws JinionException;
	
	public int getColumnIndex(String columnName){
		for (Iterator iterator = this.columns.iterator(); iterator.hasNext();) {
			TableColumn column = (TableColumn) iterator.next();
			if (column.getColumnName().equals(columnName)) {
				return column.getIndex();
			}
		}
		return -1;
	}
	
	public List<TableColumn> getColumns() {
		return columns;
	}

	public List<TableRow> getRows() {
		return rows;
	}

	/**
	 * Get the ResultSet returned by database driver.<br>
	 * It is not recommended to operate the ResultSet directly. The database connection may be closed at anytime!
	 * @return ResultSet
	 */
	public ResultSet getResultSet(){
		return this.resultSet;
	}
}
